package com.tanxi521.afkreward.util;

import com.tanxi521.afkreward.AfkReward;
import com.tanxi521.afkreward.data.AFKRewardMapper;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;

import java.util.Arrays;
import java.util.List;

// 指令处理工具
public class CommandSplUtil {

    private static String command;

    private static CommandSplUtil commandSplUtil;

    private CommandSplUtil() {
    }

    public synchronized static CommandSplUtil handle(String command, CommandSender sender) {
        if (commandSplUtil == null) commandSplUtil = new CommandSplUtil();
        commandSplUtil.init(command).placeholderApi(sender).computeCmd();
        return commandSplUtil;
    }
    private CommandSplUtil init(String command) {
        this.command = command;
        return this;
    }
    public String getCommand() {
        return command;
    }

    private CommandSplUtil placeholderApi(CommandSender sender) {
        command = PlaceholderAPI.setPlaceholders((OfflinePlayer) sender, command);
        AfkReward.getInstance().getLogger().info("§e奖励指令占位符替换: " + "§r" + command);
        return this;
    }

    private CommandSplUtil computeCmd() {
        List<String> args = Arrays.asList(command.split(" "));
        command = "";
        args.forEach(arg -> {
            if (arg.contains("+") || arg.contains("-") || arg.contains("*") || arg.contains("/")) {
                command += AFKRewardMapper.compute(arg) + " ";
            } else command += arg + " ";
        });
        AfkReward.getInstance().getLogger().info("§e指令四则运算结果: " + "§r" + command);
        return this;
    }

}
